from tornado import ioloop
from tornado.web import Application
from tornado.websocket import WebSocketHandler
# from shikuang import single_image

import base64

class EchoWebSocket(WebSocketHandler):
    users = set()

    def open(self):
        print("WebSocket opened")
        self.users.add(self)


    # 处理client发送的数据
    def on_message(self, message):
        if type(message) == str:
            value = message
            for user in self.users:
                msg = {"type": 2, "msg": value, "time": 1}
                print(msg)
                user.write_message(msg)
        else:
            for user in self.users:
                base64_data = base64.b64encode(message)
                msg = {"type": 3, "msg": str(base64_data, encoding='utf-8'), "time": 1}
                user.write_message(msg)

    def on_close(self):
        print("WebSocket closed")
        self.users.discard(self)

    # 允许所有跨域通讯，解决403问题
    def check_origin(self, origin):
        return True


if __name__ == "__main__":
    application = Application([
        (r"/", EchoWebSocket),
    ])
    application.listen(3000)
    ioloop.IOLoop.current().start()
